package com.bitauto.i.commonUtils.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLock02 {
    Lock lock = new ReentrantLock();

    public void m1() {
        lock.lock();
        try {
            System.out.println("t1 start");
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
            System.out.println("t1 end");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void m2() {
        boolean  flag = false;
        try {
            lock.lockInterruptibly();
            System.out.println("t2 start");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("t2 end");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(flag){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLock02 t = new ReentrantLock02();
        new Thread(t::m1,"t1").start();
        try {
            System.out.println("睡1秒");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Thread t2=new Thread(t::m2,"t2");
        t2.start();

        try {
            System.out.println("睡5秒");
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        t2.interrupt();
    }
}
